<template>
  <div>

    <div style="padding:15px;">
      <template v-for="(item,index) in recordValue">
        <Cell :key="index" v-if="['many2many'].indexOf(Object.values(recordValue[index])[0].type)>= 0">
          <field :model="model" :id="id" style="padding: 10px;text-align: center;alignment: center"
                 :key="index"
                 :field="Object.values(recordValue[index])[0]"
                 :value="{cval:Object.values(recordValue[index])[0].value}"
                 :edit="false"
                 :title="true" :context="context"
          />
        </Cell>
        <Cell :key="index" :title="Object.values(recordValue[index])[0].string" v-else>
          <field :model="model" :id="id" style="padding: 10px;text-align: center;alignment: center"
                 :key="index"
                 :field="Object.values(recordValue[index])[0]"
                 :value="{cval:Object.values(recordValue[index])[0].value}"
                 :edit="false"
                 :title="true" :context="context"
          />
        </Cell>
      </template>
    </div>
    <div style="position: absolute;bottom:0px;right:0px;font-size: 5px;font-weight: lighter">
      Form
    </div>
  </div>
</template>

<script>
  import {writeDict} from '../utils/util'
  import {baseField, modelMethod, msgField, ratingField, record, recordWrite, seoField, websiteField} from '../api/http'
  import gql from 'graphql-tag'
  import Field from '../Field'
  import {Cell} from 'vant'

  export default {
    name: 'Form',
    components: {
      Field, Cell
    },
    data: function () {
      return {
        datas: {},
        jfields: null,
        dataRecordForm: null,
        dataField: null,
        model: null,
        context: {},
        recordValue: [],
        id: null,
        doEdit: false,
        activeNames: [],
        result: {},
        queryFields: [],
        writeDict: {},
        otherFields: [],
        website: false,
        seo: false,
        rating: false,
        mail: false
      }
    },
    computed: {
      change() {
        if (this.recordValue) {
          for (let fieldName of this.recordValue) {
            let field = Object.values(fieldName)[0]
            if (field.change) {
              return true
            }
          }
        }
        return false
      }
    },
    watch: {
      dataRecordForm(to, from) {
        if (this.jfields && !this.doEdit) {
          let val = []
          if (this.dataRecordForm && this.dataRecordForm[0] && this.dataRecordForm[0].value) {
            for (let item in this.dataRecordForm[0].value) {
              if (item === 'context') {
                // this.context = JSON.parse(this.dataRecordForm[0].value[item])
              } else {
                let tt = {}
                tt[item] = this.jfields[item]
                tt[item]['name'] = item
                tt[item]['value'] = this.dataRecordForm[0].value[item]
                val.push(tt)
              }
            }
          }
          this.recordValue = val
          //修改导航栏标题
          console.info(this.dataRecordForm[0].value.name)
          this.$emit('onTitle', this.dataRecordForm[0].value.name)
        }
      },
      dataField: function (to, from) {
        this.refersh()
      },
      jfields(to, from) {
        this.refersh()
      },
      $route(to, from) {
        if (to.name === 'Form') {
          this.model = to.params.model
          if (to.params.id > 0) this.id = parseInt(to.params.id)
          else this.id = 0
          this.$apollo.queries.dataRecordForm.refetch()
          console.log('route changed')
        }
      }
    },

    mounted: function () {
      this.model = this.$route.params.model
      if (this.$route.params.id > 0) this.id = parseInt(this.$route.params.id)
      else this.id = 0

    },
    apollo: {
      jfields: {
        query: gql`query qdv($model:String){
          jfields:allJfield(model:$model)
          }`,
        variables() {
          return {
            model: this.model
          }
        },
        skip() {
          return !this.model
        }
      },
      dataField: {
        query: gql`query qdv($domain:String){
          dataField:allMobileModel(domain:$domain) {
              fieldsRecIds{
                name
              }
            }
          }`,
        variables() {
          return {
            domain: JSON.stringify([['model', '=', this.model]])
          }
        },
        skip() {
          return !this.model
        }

      },
      dataRecordForm() {
        return {
          query: gql`query qdv($model:String,$id:Int!,$queryFields:[String]){
                   dataRecordForm:allRecord(model:$model,id:$id,fields:$queryFields){
            value
          }
         }`,
          variables() {
            return {
              model: this.model,
              id: this.id,
              queryFields: this.queryFields
            }
          },
          skip() {
            return !(this.jfields && this.dataField && this.model && this.id && this.queryFields)
          }
        }
      }
    },
    methods: {
      refersh() {
        if (this.dataField && this.jfields && !this.doEdit) {
          let val = []
          let other = []
          let dfields = this.dataField[0] && this.dataField[0].fieldsRecIds ? this.dataField[0].fieldsRecIds.map(x => x.name) : []
          for (let item of Object.keys(this.jfields)) {
            if (websiteField.indexOf(item) >= 0) {
              this.website = true
            } else if (baseField.indexOf(item) >= 0) {
              // this.website = true
            } else if (seoField.indexOf(item) >= 0) {
              this.seo = true
            } else if (ratingField.indexOf(item) >= 0) {
              this.rating = true
            } else if (msgField.indexOf(item) >= 0) {
              this.mail = true
            } else if (dfields.indexOf(item) >= 0 || item === 'id' || item === 'display_name' || item === 'context') {
              val.push(item)
            } else {
              let v = {}
              v[item] = this.jfields[item]
              other.push(v)
            }
          }
          this.queryFields = val
          this.otherFields = other
        }
      },
      switchData(id) {

      },
      toggle(field) {
        field.value = !field.value
      },
      cancel: function () {
        this.$router.back()

      },

      saveRecord: function () {
        this.writeDict = writeDict(this.recordValue)
        this.$apollo.mutate({
          mutation: gql`mutation($id:Int!,$model:String!,$value:JSON!){
  writeRecord(id:$id,model:$model,value:$value){
    ok
  }
}`,
          variables: {id: this.id, model: this.model, value: this.writeDict}
        })
          .then(function (response) {
            if (response && response.writeRecord.ok) {
              // self.app_root.toast(response.result.errMsg)
              // self.$router ? self.$router.back() : window.history.back()
            } else if (response && !response.writeRecord.ok) {
              // self.app_root.toast(response.result.errMsg)
            }
          })
          .catch(function (error) {
            console.log(error, __filename)
          })
      },
      saveClose: function () {
        let self = this
        this.writeDict = writeDict(this.recordValue)
        recordWrite(this.model, this.writeDict)
          .then(function (response) {
            if (response && response.result.success) {
              // self.app_root.toast(response.result.errMsg)
              self.$router.back()

            } else if (response && !response.result.success) {
              // self.app_root.toast(response.result.errMsg)
            }
          })
          .catch(function (error) {
            console.log(error, __filename)
          })
      },
      saveLayout: function () {
        let self = this
        let fields = this.recordValue.map(x => Object.keys(x)[0])
        modelMethod('mobile.model', 'set_field_name', [this.model, 'record', fields]).then(
          function (reponse) {
            self.doEdit = false
          },
          function (error) {
            console.error(error)
          }
        )
      }
    }
    // beforeRouteEnter (to, from, next) {
    //   const model = to.params.model
    //   if (model) {
    //     next(instance => instance.switchData(model))
    //   } else {
    //     next(new Error('未指定ID'))
    //   }
    // },
    // // 在同一组件对应的多个路由间切换时触发
    // beforeRouteUpdate (to, from, next) {
    //   const model = to.params.model + to.params.id
    //   if (model) {
    //     this.switchData(model)
    //     next()
    //   } else {
    //     next(new Error('未指定ID'))
    //   }
    // }
  }
</script>
